<template>
	<view class="container">
		
		<!-- 视图切换按钮 -->
		<view class="view-switch">
			<view 
				class="switch-btn" 
				:class="{active: viewMode === 'calendar'}"
				@click="switchView('calendar')"
			>
				日历视图
			</view>
			<view 
				class="switch-btn" 
				:class="{active: viewMode === 'list'}"
				@click="switchView('list')"
			>
				列表视图
			</view>
		</view>
		
		<!-- 日历视图 -->
		<view class="calendar-section" v-if="viewMode === 'calendar'">
			<view class="calendar-header">
				<view class="calendar-nav">
					<view class="nav-btn" @click="prevMonth">‹</view>
					<text class="current-month">{{currentYear}}年{{currentMonth + 1}}月</text>
					<view class="nav-btn" @click="nextMonth">›</view>
				</view>
			</view>
			
			<view class="calendar-weekdays">
				<view class="weekday" v-for="day in weekDays" :key="day">{{day}}</view>
			</view>
			
			<view class="calendar-days">
				<view 
					class="calendar-day" 
					v-for="day in calendarDays" 
					:key="day.date"
					:class="{
						'other-month': !day.isCurrentMonth,
						'today': isToday(day.date),
						'has-reminder': day.hasReminder,
						'selected': isSelected(day.date)
					}"
					@click="selectDate(day)"
				>
					<text class="day-number">{{day.day}}</text>
					<view class="reminder-dot" v-if="day.hasReminder"></view>
				</view>
			</view>
		</view>
		
		<!-- 选中日期的提醒 -->
			<view class="reminder-section" v-if="viewMode === 'calendar' && selectedDateRemindersWithStatus.length > 0">
				<view class="section-title">
					{{formatSelectedDate()}} 的提醒
				</view>
				<view class="reminder-list">
					<view 
						class="reminder-item" 
						v-for="reminder in selectedDateRemindersWithStatus" 
						:key="reminder.id"
						@click="viewReminderDetail(reminder.id)"
					>
						<view class="reminder-icon">
							<text class="icon">{{getReminderIcon(reminder.reminderType)}}</text>
						</view>
						<view class="reminder-info">
							<view class="reminder-type-container">
								<view class="reminder-type-highlight">{{reminder.reminderType}}</view>
								<view class="reminder-pet-highlight">{{getPetName(reminder.petId)}}</view>
							</view>
							<view class="reminder-header">
								<view class="reminder-title">{{reminder.title}}</view>
								<text class="reminder-status" :class="getStatusClass(reminder.status, reminder)">{{getStatusText(reminder.status, reminder)}}</text>
							</view>
							<view class="reminder-details">
								<text class="reminder-repeat" v-if="reminder.repeatType && reminder.repeatType !== '不重复'">{{getRepeatTypeLabel(reminder.repeatType)}}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 空状态 -->
			<view class="empty-state" v-else-if="viewMode === 'calendar' && !loading && selectedDate && selectedDateRemindersWithStatus.length === 0">
			<text class="empty-text">该日期暂无提醒</text>
		</view>
		
		<!-- 列表视图 -->
		<view class="list-view" v-if="viewMode === 'list'">
			<view class="section-title">
				提醒列表
			</view>
			<view class="reminder-list">
				<view 
					class="list-item" 
					v-for="reminder in reminderList" 
					:key="reminder.id"
					@click="viewReminderDetail(reminder.id)"
				>
					<view class="list-item-header">
							<view class="list-item-title">{{reminder.title}}</view>
							<view class="list-item-pet">{{getPetName(reminder.petId)}}</view>
							<text class="list-item-status" :class="getStatusClass(reminder.status, reminder)">{{getStatusText(reminder.status, reminder)}}</text>
						</view>
					<view class="list-item-info">
					<text class="list-item-time">{{formatDateTime(reminder.reminderTime)}}</text>
					<text class="list-item-repeat" v-if="reminder.repeatType && reminder.repeatType !== '不重复'">{{getRepeatTypeLabel(reminder.repeatType)}}</text>
				</view>
				</view>
			</view>
			
			<!-- 列表视图空状态 -->
			<view class="empty-state" v-if="!loading && reminderList.length === 0">
				<text class="empty-text">暂无提醒</text>
			</view>
		</view>
		
		<!-- 加载状态 -->
		<view class="loading-state" v-if="loading">
			<text class="loading-text">加载中...</text>
		</view>
		
		<!-- 悬浮添加按钮 -->
		<view class="fab" @click="addReminder">
			<text class="fab-icon">+</text>
		</view>
	</view>
</template>

<script>
import { getUserId, checkAndRedirectToLogin } from '@/utils/auth.js'
import { getPetList } from '@/api/pet.js'
import { getreminderlist, deletereminder } from '@/api/reminder.js'
import { getDictData } from '@/api/dict.js'

export default {
	data() {
		return {
			loading: false,
			reminders: [],
			pets: [],
			currentFilter: 'all',
			petId: null,
			viewMode: 'calendar', // 'calendar' 或 'list'
			// 日历相关数据
			currentYear: new Date().getFullYear(),
			currentMonth: new Date().getMonth(),
			selectedDate: new Date(),
			calendarDays: [],
			weekDays: ['日', '一', '二', '三', '四', '五', '六'],
			// 重复类型字典数据
			repeatTypes: [],
			repeatTypeLabels: [],
			// 目标提醒ID和健康记录ID
			targetReminderId: null,
			targetHealthRecordId: null,
			// 带有健康记录状态的选中日期提醒列表
			selectedDateRemindersWithStatus: []
		}
	},
	computed: {
		filteredRecords() {
			if (this.currentFilter === 'all') {
				return this.reminders
			}
			return this.reminders.filter(record => record.reminderType === this.currentFilter)
		},
		totalRecords() {
			return this.reminders.length
		},
		reminderCount() {
			return this.reminders.filter(record => record.reminderTime).length
		},
		completedCount() {
			return this.reminders.filter(record => this.isCompletedStatus(record.status)).length
		},
		// 列表视图的提醒
		reminderList() {
			// 获取今天的日期，重置时间为0点
			const today = new Date()
			const todayOnly = new Date(today.getFullYear(), today.getMonth(), today.getDate())
			
			return this.reminders.filter(record => {
				// 检查提醒是否启用
				if (record.isEnabled === false || record.isEnabled === 0 || record.isEnabled === 'false') {
					return false
				}
				
				// 显示有提醒时间的记录（包括待处理和已完成状态）
				if (record.reminderTime) {
					const remindDate = new Date(record.reminderTime)
					const remindDateOnly = new Date(remindDate.getFullYear(), remindDate.getMonth(), remindDate.getDate())
					
					// 检查提醒日期是否大于等于今天
					if (remindDateOnly < todayOnly) {
						return false
					}
					
					return true
				}
				return false
			}).sort((a, b) => {
				// 按提醒时间排序
				return new Date(a.reminderTime) - new Date(b.reminderTime)
			})
		}
	},
	onLoad(options) {
		console.log('日历页面onLoad开始执行，参数:', options)
		
		// 处理从健康记录页面跳转过来的参数
		if (options.reminderId) {
			this.targetReminderId = options.reminderId
			console.log('设置targetReminderId:', this.targetReminderId)
		}
		if (options.healthRecordId) {
			this.targetHealthRecordId = options.healthRecordId
			console.log('设置targetHealthRecordId:', this.targetHealthRecordId)
		}
		
		console.log('开始加载宠物数据和字典数据')
		this.loadPets()
		this.loadDictData()
		// 监听提醒更新事件
		uni.$on('reminderupdated', () => {
			console.log('收到提醒更新事件')
			this.loadReminders().then(() => {
				this.initSelectedDateReminders()
			})
		})
		
		// 页面初次加载时加载提醒数据
		this.loadReminders().then(() => {
			this.initSelectedDateReminders()
		})
		console.log('日历页面onLoad执行完成')
	},
	onShow() {
		console.log('日历页面onShow开始执行')
		this.loadReminders().then(() => {
			// 加载提醒数据后，初始化选中日期的提醒列表
			this.initSelectedDateReminders()
		})
		console.log('日历页面onShow执行完成')
	},
	watch: {
		reminders: {
			handler() {
				this.generateCalendar()
			},
			immediate: true
		},
		currentMonth() {
			this.generateCalendar()
		},
		currentYear() {
			this.generateCalendar()
		}
	},
	onUnload() {
		// 移除事件监听
		uni.$off('reminderupdated')
	},
	onReady() {
	},
	methods: {
		// 加载字典数据
		async loadDictData() {
			try {
				const response = await getDictData('repeat_type')
				if (response && response.code === 200) {
					const dictData = response.data || []
					this.repeatTypes = dictData
					this.repeatTypeLabels = dictData.map(item => item.dictLabel)
					console.log('重复类型字典数据加载成功:', this.repeatTypes)
				} else {
					console.error('重复类型字典数据加载失败:', response)
					// 使用默认值
					this.repeatTypes = [
						{ dictLabel: '不重复', dictValue: '0' },
						{ dictLabel: '每天', dictValue: '1' },
						{ dictLabel: '每周', dictValue: '2' },
						{ dictLabel: '每月', dictValue: '3' },
						{ dictLabel: '每年', dictValue: '4' }
					]
					this.repeatTypeLabels = this.repeatTypes.map(item => item.dictLabel)
				}
			} catch (error) {
				console.error('重复类型字典数据加载异常:', error)
				// 使用默认值
				this.repeatTypes = [
					{ dictLabel: '不重复', dictValue: '0' },
					{ dictLabel: '每天', dictValue: '1' },
					{ dictLabel: '每周', dictValue: '2' },
					{ dictLabel: '每月', dictValue: '3' },
					{ dictLabel: '每年', dictValue: '4' }
				]
				this.repeatTypeLabels = this.repeatTypes.map(item => item.dictLabel)
			}
		},
		
		// 生成日历
		generateCalendar() {
			console.log('generateCalendar开始执行')
			console.log('当前年月:', this.currentYear, this.currentMonth)
			
			const year = this.currentYear
			const month = this.currentMonth
			
			// 获取当月第一天
			const firstDay = new Date(year, month, 1)
			// 获取当月最后一天
			const lastDay = new Date(year, month + 1, 0)
			// 获取第一天是周几（0为周日）
			const firstDayWeek = firstDay.getDay()
			// 获取最后一天是周几
			const lastDayWeek = lastDay.getDay()
			
			console.log('日历参数:', {year, month, firstDayWeek, lastDayWeek})
			
			const days = []
			
			// 添加上个月的最后几天
			const prevMonthLastDay = new Date(year, month, 0).getDate()
			for (let i = firstDayWeek - 1; i >= 0; i--) {
				const day = prevMonthLastDay - i
				const date = new Date(year, month - 1, day)
				days.push({
					day,
					date: this.formatDate(date),
					isCurrentMonth: false,
					hasReminder: this.hasReminderOnDate(date)
				})
			}
			
			// 添加当月的所有天
			for (let i = 1; i <= lastDay.getDate(); i++) {
				const date = new Date(year, month, i)
				days.push({
					day: i,
					date: this.formatDate(date),
					isCurrentMonth: true,
					hasReminder: this.hasReminderOnDate(date)
				})
			}
			
			// 添加下个月的前几天
			for (let i = 1; i <= 6 - lastDayWeek; i++) {
				const date = new Date(year, month + 1, i)
				days.push({
					day: i,
					date: this.formatDate(date),
					isCurrentMonth: false,
					hasReminder: this.hasReminderOnDate(date)
				})
			}
			
			console.log('生成的日历天数:', days.length)
			this.calendarDays = days
			console.log('generateCalendar执行完成')
		},
		
		// 检查指定日期是否有提醒
		hasReminderOnDate(date) {
			const dateStr = this.formatDate(date)
			const checkDate = new Date(date)
			
			// 获取今天的日期，重置时间为0点
			const today = new Date()
			const todayOnly = new Date(today.getFullYear(), today.getMonth(), today.getDate())
			const checkDateOnly = new Date(checkDate.getFullYear(), checkDate.getMonth(), checkDate.getDate())
			
			// 如果检查的日期小于今天，不显示红点
			if (checkDateOnly < todayOnly) {
				return false
			}
			
			return this.reminders.some(record => {
				// 检查提醒是否启用
				if (record.isEnabled === false || record.isEnabled === 0 || record.isEnabled === 'false') {
					return false
				}
				
				// 显示有提醒时间的记录（包括待处理和已完成状态）
				if (record.reminderTime) {
					const remindDate = new Date(record.reminderTime)
					const repeatType = record.repeatType
					
					// 如果没有重复类型或者重复类型为'不重复'，只检查原始提醒日期
					if (!repeatType || repeatType === '不重复') {
						// 检查提醒日期是否大于等于今天
						const remindDateOnly = new Date(remindDate.getFullYear(), remindDate.getMonth(), remindDate.getDate())
						return remindDateOnly >= todayOnly && this.formatDate(remindDate) === dateStr
					}
					
					// 检查重复提醒：检查日期是否符合重复规则
					const repeatTypeObj = this.repeatTypes.find(item => item.dictValue === repeatType)
					const repeatTypeLabel = repeatTypeObj ? repeatTypeObj.dictLabel : repeatType
					
					switch (repeatTypeLabel) {
						case '每天':
						// 每天重复，检查日期是否大于等于提醒日期且大于等于今天
						const remindDateOnlyDaily = new Date(remindDate.getFullYear(), remindDate.getMonth(), remindDate.getDate())
						return checkDateOnly >= remindDateOnlyDaily && checkDateOnly >= todayOnly
							
						case '每周':
						// 每周重复，检查是否为同一天（周几）且提醒日期大于等于今天
						const remindDateOnlyWeekly = new Date(remindDate.getFullYear(), remindDate.getMonth(), remindDate.getDate())
						return remindDateOnlyWeekly >= todayOnly && checkDate.getDay() === remindDate.getDay()
						
						case '每月':
						// 每月重复，检查是否为同一天（每月的第几天）且提醒日期大于等于今天
						const remindDateOnlyMonthly = new Date(remindDate.getFullYear(), remindDate.getMonth(), remindDate.getDate())
						return remindDateOnlyMonthly >= todayOnly && checkDate.getDate() === remindDate.getDate()
						
						case '每年':
						// 每年重复，检查是否为同月同日且提醒日期大于等于今天
						const remindDateOnlyYearly = new Date(remindDate.getFullYear(), remindDate.getMonth(), remindDate.getDate())
						return remindDateOnlyYearly >= todayOnly && checkDate.getDate() === remindDate.getDate() && 
						       checkDate.getMonth() === remindDate.getMonth()
							
						default:
							const remindDateOnlyDefault = new Date(remindDate.getFullYear(), remindDate.getMonth(), remindDate.getDate())
							return remindDateOnlyDefault >= todayOnly && this.formatDate(remindDate) === dateStr
					}
				}
				return false
			})
		},
		
		// 选择日期
		async selectDate(day) {
			this.selectedDate = new Date(day.date)
			// 获取选中日期的提醒列表并添加健康记录状态
			this.selectedDateRemindersWithStatus = await this.getSelectedDateReminders()
		},
		
		// 判断是否为今天
		isToday(date) {
			const today = new Date()
			const dateObj = new Date(date)
			return dateObj.getDate() === today.getDate() &&
			       dateObj.getMonth() === today.getMonth() &&
			       dateObj.getFullYear() === today.getFullYear()
		},
		
		// 判断是否为选中的日期
		isSelected(date) {
			if (!this.selectedDate) return false
			const dateObj = new Date(date)
			const selectedObj = new Date(this.selectedDate)
			return dateObj.getDate() === selectedObj.getDate() &&
			       dateObj.getMonth() === selectedObj.getMonth() &&
			       dateObj.getFullYear() === selectedObj.getFullYear()
		},
		
		// 上一个月
		prevMonth() {
			if (this.currentMonth === 0) {
				this.currentMonth = 11
				this.currentYear--
			} else {
				this.currentMonth--
			}
		},
		
		// 下一个月
		nextMonth() {
			if (this.currentMonth === 11) {
				this.currentMonth = 0
				this.currentYear++
			} else {
				this.currentMonth++
			}
		},
		
		// 格式化日期为 YYYY-MM-DD
		formatDate(date) {
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			return `${year}-${month}-${day}`
		},
		
		// 格式化选中的日期
		formatSelectedDate() {
			if (!this.selectedDate) return ''
			const date = new Date(this.selectedDate)
			return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
		},
		
		// 切换视图
		switchView(mode) {
			this.viewMode = mode
		},
		
		// 获取宠物名称
		getPetName(petId) {
			if (!petId) return '未知宠物'
			// 处理数据类型不匹配问题：petId可能是字符串或数字
			const pet = this.pets.find(p => {
				// 将两个id都转换为字符串进行比较
				return String(p.id) === String(petId)
			})
			return pet ? pet.name : '未知宠物'
		},
		
		async loadPets() {
			try {
				// 使用统一的认证检查函数
				if (!checkAndRedirectToLogin('请先登录')) {
					return
				}
				
				const userId = getUserId()
				const response = await getPetList(userId)
				
				if (response && response.code === 200) {
					const petData = response.rows || response.data || []
					this.pets = petData
				}
			} catch (error) {
				
			}
		},
		
		async loadReminders() {
		console.log('loadReminders开始执行')
		this.loading = true
		try {
			console.log('正在获取提醒列表...')
			const response = await getreminderlist({
				pageNum: 1,
				pageSize: 100
			})
			console.log('获取提醒列表响应:', response)
			
			// 使用统一API后的响应格式
			if (response && response.code === 200) {
				const data = response.rows || response.data || []
				console.log('解析到的提醒数据:', data)
				
				if (data && data.length > 0) {
					// 直接赋值
					this.reminders = data
					console.log('设置reminders数组，长度:', this.reminders.length)
				} else {
					this.reminders = []
					console.log('没有提醒数据，设置空数组')
				}
			} else {
				this.reminders = []
				console.log('API响应异常，设置空数组')
			}
		} catch (error) {
			console.error('获取提醒列表异常:', error)
			this.reminders = []
		} finally {
			this.loading = false
			console.log('loadReminders执行完成，loading状态:', this.loading)
			
			// 处理目标提醒定位
			if (this.targetReminderId || this.targetHealthRecordId) {
				console.log('开始定位目标提醒')
				this.locateTargetReminder()
			}
		}
	},
		
		filterRecords(filter) {
			this.currentFilter = filter
		},
		
		getReminderIcon(type) {
			const icons = {
				'疫苗': '💉',
				'驱虫': '🦠',
				'体检': '🏥',
				'体重': '⚖️',
				'喂药': '💊',
				'洗澡': '🛁',
				'美容': '✂️',
				'运动': '🏃',
				'其他': '📋'
			}
			return icons[type] || '📋'
		},
		// 定位目标提醒
	locateTargetReminder() {
		console.log('locateTargetReminder开始执行')
		console.log('reminders数组长度:', this.reminders ? this.reminders.length : 0)
		console.log('targetReminderId:', this.targetReminderId)
		console.log('targetHealthRecordId:', this.targetHealthRecordId)
		
		if (!this.reminders || this.reminders.length === 0) {
			console.log('reminders数组为空，无法定位')
			return
		}
		
		let targetReminder = null
		
		// 优先通过reminderId查找
		if (this.targetReminderId) {
			targetReminder = this.reminders.find(r => String(r.id) === String(this.targetReminderId))
			console.log('通过reminderId查找结果:', targetReminder)
		}
		
		// 如果没找到，尝试通过healthRecordId查找
		if (!targetReminder && this.targetHealthRecordId) {
			targetReminder = this.reminders.find(r => String(r.healthRecordId) === String(this.targetHealthRecordId))
			console.log('通过healthRecordId查找结果:', targetReminder)
		}
		
		if (targetReminder && targetReminder.reminderTime) {
			console.log('找到目标提醒:', targetReminder)
			console.log('当前viewMode:', this.viewMode)
			
			// 切换到日历视图
			this.viewMode = 'calendar'
			console.log('切换viewMode为calendar')
			
			// 设置选中日期为提醒日期
			const reminderDate = new Date(targetReminder.reminderTime)
			this.selectedDate = reminderDate
			console.log('设置selectedDate:', reminderDate)
			
			// 设置日历显示到对应的月份
			this.currentYear = reminderDate.getFullYear()
			this.currentMonth = reminderDate.getMonth()
			console.log('设置currentYear和currentMonth:', this.currentYear, this.currentMonth)
			
			// 延迟一下确保日历更新完成
			setTimeout(() => {
				console.log('延迟执行，重新生成日历')
				// 重新生成日历
				this.generateCalendar()
				console.log('generateCalendar执行完成')
				
				// 显示提示
				uni.showToast({
					title: '已定位到对应提醒',
					icon: 'success',
					duration: 2000
				})
			}, 300)
		} else {
			console.log('未找到目标提醒或reminderTime为空')
			// 如果没找到对应的提醒，显示提示
			uni.showToast({
				title: '未找到对应的提醒',
				icon: 'none',
				duration: 2000
			})
		}
		
		// 清空目标ID，避免重复定位
		this.targetReminderId = null
		this.targetHealthRecordId = null
		console.log('清空目标ID，locateTargetReminder执行完成')
	},
		
		isPendingStatus(status) {
			// 统一判断待处理状态：支持数字0、字符串'0'、英文'pending'
			return status === '0' || status === 0 || status === 'pending'
		},
		isCompletedStatus(status) {
			// 统一判断已完成状态：支持数字1、字符串'1'、英文'completed'
			return status === '1' || status === 1 || status === 'completed'
		},
		
		// 检查提醒是否有对应的健康记录
		hasHealthRecord(reminder) {
			// 根据实际数据结构判断是否有健康记录
			// 1. 如果提醒有healthRecordId字段，说明已生成健康记录
			// 2. 如果提醒状态为已完成，也可能说明有健康记录
			// 3. 或者有其他标记字段
			
			return reminder.healthRecordId || 
			       reminder.hasHealthRecord || 
			       (reminder.status && this.isCompletedStatus(reminder.status)) ||
			       false
		},
		
		// 检查指定日期的健康记录
		async checkHealthRecordForDate(reminder, targetDate) {
			console.log('Calendar - checkHealthRecordForDate called')
			console.log('Calendar - Reminder:', JSON.stringify(reminder))
			console.log('Calendar - Check date:', targetDate)
			console.log('Calendar - Check date type:', typeof targetDate)
			
			try {
				if (!reminder || !reminder.id) {
					return false
				}
				
				// 导入健康记录API
				const { getHealthList } = await import('@/api/health.js')
				
				// 使用目标日期或当前日期
				const checkDate = targetDate || new Date()
				const checkDateStr = checkDate.toISOString().slice(0, 10) // YYYY-MM-DD格式
				console.log('Calendar - Check date string:', checkDateStr)
				
				// 查询健康记录列表，只传递reminderId
				const params = {
					reminderId: reminder.id
				}
				
				const response = await getHealthList(params)
				console.log('Calendar - Health record check response for reminder', reminder.id, ':', response)
					console.log('Calendar - Response data:', response)
					console.log('Calendar - Response data rows:', response ? response.rows : 'undefined')
					console.log('Calendar - Response data rows type:', response && response.rows ? typeof response.rows : 'undefined')
					console.log('Calendar - Response data rows length:', response && response.rows ? response.rows.length : 'undefined')
					
					if (response && response.code === 200 && response && response.rows) {
						console.log('Calendar - Target date:', checkDateStr)
						console.log('Calendar - Total health records:', response.rows.length)
						console.log('Calendar - Health records array:', Array.isArray(response.rows))
						console.log('Calendar - Health records content:', JSON.stringify(response.rows))
						
						// 查找指定日期的健康记录
						const targetDateRecords = response.rows.filter(record => {
						console.log('Calendar - Processing health record:', JSON.stringify(record))
						console.log('Calendar - Record recordDate field:', record.recordDate)
						console.log('Calendar - Record recordDate type:', typeof record.recordDate)
						
						// 安全地处理recordDate，确保它是有效的日期
						let recordDate
						try {
							if (!record.recordDate) {
								console.log('Calendar - Record has no recordDate field')
								return false
							}
							// 使用本地时区处理日期，避免toISOString()的时区问题
								const dateObj = new Date(record.recordDate)
								recordDate = `${dateObj.getFullYear()}-${String(dateObj.getMonth() + 1).padStart(2, '0')}-${String(dateObj.getDate()).padStart(2, '0')}`
						} catch (e) {
							console.log('Calendar - Error parsing recordDate:', e)
							return false
						}
						
						// 使用严格相等比较，并确保类型一致
							const reminderMatch = String(record.reminderId) === String(reminder.id)
							console.log('Calendar - Reminder ID comparison:', {
								'record.reminderId': record.reminderId,
								'record.reminderId (string)': String(record.reminderId),
								'reminder.id': reminder.id,
								'reminder.id (string)': String(reminder.id),
								'match': reminderMatch
							})
						
						// 对于每周提醒，检查本周内的健康记录
						let dateMatch = false
						if (reminder.repeatType === '2' || reminder.repeatType === '每周') {
							// 获取健康记录日期和目标日期的周几
							const recordDayOfWeek = new Date(record.recordDate).getDay()
							const targetDayOfWeek = checkDate.getDay()
							// 检查是否为同一天（周几）
							dateMatch = recordDayOfWeek === targetDayOfWeek
							console.log('Calendar - Weekly reminder check: record day', recordDayOfWeek, 'target day', targetDayOfWeek, 'match:', dateMatch)
						} else {
							// 对于其他类型的提醒，检查具体日期
							dateMatch = recordDate === checkDateStr
						}
						
						console.log('Calendar - Record date:', record.recordDate, '->', recordDate)
						console.log('Calendar - Target date:', checkDateStr)
						console.log('Calendar - Date match:', dateMatch, 'Reminder match:', reminderMatch)
						console.log('Calendar - Will include record:', dateMatch && reminderMatch)
						
						return dateMatch && reminderMatch
					})
					
					console.log('Calendar - Filtered records count:', targetDateRecords.length)
						console.log('Calendar - Filtered records:', JSON.stringify(targetDateRecords))
						console.log('Calendar - Final result (has health record):', targetDateRecords.length > 0)
						
						// 如果没有找到匹配的记录，输出所有记录的日期信息以便调试
						if (targetDateRecords.length === 0) {
							console.log('Calendar - No matching records found. All record dates:')
							response.rows.forEach((record, index) => {
								console.log('Calendar - Record', index, 'date:', record.recordDate)
							})
						}
						
						return targetDateRecords.length > 0
				}
				
				return false
			} catch (error) {
				console.error('Calendar - 检查健康记录失败:', error)
				return false
			}
		},
		
		// 获取提醒的实际状态（考虑健康记录）
		getActualStatus(reminder) {
			// 优先使用通过checkHealthRecordForDate查询到的实际健康记录状态
			if (reminder.hasOwnProperty('hasHealthRecord')) {
				return reminder.hasHealthRecord ? '1' : '0' // 已完成或待处理
			}
			// 如果没有查询结果，则使用原来的逻辑
			if (this.hasHealthRecord(reminder)) {
				return '1' // 已完成
			}
			return '0' // 待处理
		},
		
		// 初始化选中日期的提醒列表
		async initSelectedDateReminders() {
			if (this.selectedDate) {
				this.selectedDateRemindersWithStatus = await this.getSelectedDateReminders()
				console.log('初始化选中日期提醒列表完成，数量:', this.selectedDateRemindersWithStatus.length)
			}
		},
		
		// 获取选中日期的提醒（包含健康记录状态）
		async getSelectedDateReminders() {
			if (!this.selectedDate) return []
			const selectedDateStr = this.formatDate(this.selectedDate)
			const checkDate = new Date(this.selectedDate)
			
			// 获取今天的日期，重置时间为0点
			const today = new Date()
			const todayOnly = new Date(today.getFullYear(), today.getMonth(), today.getDate())
			const checkDateOnly = new Date(checkDate.getFullYear(), checkDate.getMonth(), checkDate.getDate())
			
			// 如果选中的日期小于今天，不显示任何提醒
			if (checkDateOnly < todayOnly) {
				return []
			}
			
			const filteredReminders = this.reminders.filter(record => {
				// 检查提醒是否启用
				if (record.isEnabled === false || record.isEnabled === 0 || record.isEnabled === 'false') {
					return false
				}
				
				// 显示有提醒时间的记录（包括待处理和已完成状态）
				if (record.reminderTime) {
					const remindDate = new Date(record.reminderTime)
					const repeatType = record.repeatType
					
					// 如果没有重复类型或者重复类型为'不重复'，只检查原始提醒日期
					if (!repeatType || repeatType === '不重复' || repeatType === '0') {
						// 检查提醒日期是否大于等于今天
						const remindDateOnly = new Date(remindDate.getFullYear(), remindDate.getMonth(), remindDate.getDate())
						return remindDateOnly >= todayOnly && this.formatDate(remindDate) === selectedDateStr
					}
					
					// 检查重复提醒：检查日期是否符合重复规则（需在提醒日期或之后）
					const repeatTypeObj = this.repeatTypes.find(item => item.dictValue === repeatType)
					const repeatTypeLabel = repeatTypeObj ? repeatTypeObj.dictLabel : repeatType
					
					switch (repeatTypeLabel) {
						case '每天':
						// 每天重复，检查日期是否在提醒日期或之后，并且大于等于今天
						return checkDate >= remindDate && checkDateOnly >= todayOnly
							
						case '每周':
						// 每周重复，检查是否为同一天（周几）且在提醒日期或之后，并且大于等于今天
						return checkDate >= remindDate && checkDateOnly >= todayOnly && checkDate.getDay() === remindDate.getDay()
							
						case '每月':
						// 每月重复，检查是否为同一天（每月的第几天）且在提醒日期或之后，并且大于等于今天
						return checkDate >= remindDate && checkDateOnly >= todayOnly && checkDate.getDate() === remindDate.getDate()
							
						case '每年':
						// 每年重复，检查是否为同月同日且在提醒日期或之后，并且大于等于今天
						return checkDate >= remindDate && checkDateOnly >= todayOnly && checkDate.getDate() === remindDate.getDate() && 
						       checkDate.getMonth() === remindDate.getMonth()
							
						default:
							const remindDateOnly = new Date(remindDate.getFullYear(), remindDate.getMonth(), remindDate.getDate())
							return remindDateOnly >= todayOnly && this.formatDate(remindDate) === selectedDateStr
					}
				}
				return false
			})
			
			// 为过滤后的提醒添加健康记录状态
			return await this.addHealthRecordStatus(filteredReminders, this.selectedDate)
		},
		
		// 为提醒添加健康记录状态信息
		async addHealthRecordStatus(reminders, targetDate) {
			if (!reminders || reminders.length === 0) {
				return reminders
			}
			
			console.log('Calendar - Adding health record status to', reminders.length, 'reminders')
			console.log('Calendar - Target date:', targetDate ? targetDate.toISOString().slice(0, 10) : 'undefined')
			
			// 为每个提醒检查健康记录状态
			const remindersWithStatus = await Promise.all(reminders.map(async (reminder) => {
				const hasHealthRecord = await this.checkHealthRecordForDate(reminder, targetDate)
				const reminderWithStatus = {
					...reminder,
					hasHealthRecord: hasHealthRecord
				}
				console.log('Calendar - Reminder', reminder.id, 'health record status:', hasHealthRecord)
				console.log('Calendar - Reminder with status:', reminderWithStatus)
				return reminderWithStatus
			}))
			
			console.log('Calendar - Final reminders with status:', remindersWithStatus)
			return remindersWithStatus
		},
		
		getStatusText(status, reminder) {
			// 获取状态文本，如果有reminder参数则使用实际状态
			const actualStatus = reminder ? this.getActualStatus(reminder) : status
			let statusText = ''
			if (this.isPendingStatus(actualStatus)) {
				statusText = '待处理'
			} else if (this.isCompletedStatus(actualStatus)) {
				statusText = '已完成'
			} else {
				statusText = '未知状态'
			}
			
			// 添加调试日志
			if (reminder) {
				console.log('Calendar - getStatusText for reminder', reminder.id)
				console.log('Calendar - hasHealthRecord property:', reminder.hasHealthRecord)
				console.log('Calendar - Actual status:', actualStatus)
				console.log('Calendar - Status text:', statusText)
			}
			
			return statusText
		},
		
		getStatusClass(status, reminder) {
			// 获取状态样式类，如果有reminder参数则使用实际状态
			const actualStatus = reminder ? this.getActualStatus(reminder) : status
			if (this.isPendingStatus(actualStatus)) {
				return 'status-pending'
			} else if (this.isCompletedStatus(actualStatus)) {
				return 'status-completed'
			}
			return 'status-unknown'
		},
		
		formatDateTime(dateTime) {
			if (!dateTime) return ''
			const date = new Date(dateTime)
			return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
		},
		
		getRepeatTypeLabel(repeatType) {
			// 查找匹配的dictValue
			const repeatTypeObj = this.repeatTypes.find(item => item.dictValue === repeatType)
			if (repeatTypeObj) {
				return repeatTypeObj.dictLabel
			}
			// 如果没找到，返回原始值
			return repeatType || '不重复'
		},
		
		viewReminderDetail(recordId) {
			// 传递选中的日期参数，让detail页面知道要检查哪个日期的健康记录
			const selectedDateStr = this.selectedDate ? this.formatDate(this.selectedDate) : ''
			uni.navigateTo({
				url: `/pages/calendar/detail?id=${recordId}&date=${selectedDateStr}`
			})
		},
		
		editReminder(recordId) {
			
			uni.navigateTo({
				url: `/pages/calendar/edit?id=${recordId}`,
				success: (res) => {
					
				},
				fail: (err) => {
					
					uni.showToast({
						title: '无法打开编辑页面',
					icon: 'none'
				});
				}
			});
		},
		
		addReminder() {
			uni.navigateTo({
				url: '/pages/calendar/add'
			})
		},
		
		async deleteReminder(recordId) {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这个提醒吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							const response = await deletereminder(recordId)
							
							// 处理 uni.request 的响应格式
							let responseData = response
							
							// 如果响应是数组格式 [error, response]，取第二个元素
							if (Array.isArray(response) && response.length === 2) {
								const [error, data] = response
								if (error) {
									
									uni.showToast({
										title: '网络请求失败',
										icon: 'none'
									})
									return
								}
								responseData = data
							}
							
							// 检查响应状态
							if (responseData && responseData.code === 200) {
								const data = responseData.data
								
								// 删除成功通常返回 code: 200
								if (data && data.code === 200) {
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									})
									// 重新加载列表
									this.loadReminders()
								} else {
									// 即使业务逻辑返回失败，如果HTTP状态是200，说明请求成功
									// 可能是后端删除成功但返回了其他状态码
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									})
									this.loadReminders()
								}
							} else {
								// HTTP错误
								uni.showToast({
									title: '删除失败',
									icon: 'none'
								})
							}
						} catch (error) {
							
							uni.showToast({
								title: '删除失败',
								icon: 'none'
							})
						}
					}
				}
			})
		}
	} // End of methods
}
</script>

<style scoped>
.container {
	padding: 20rpx;
	background-color: #f5f5f5;
	min-height: 100vh;
}

/* 视图切换样式 */
.view-switch {
	display: flex;
	background: white;
	border-radius: 25rpx;
	padding: 8rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.switch-btn {
	flex: 1;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 20rpx;
	font-size: 26rpx;
	color: #666;
	transition: all 0.3s ease;
	cursor: pointer;
}

.switch-btn.active {
	background: #007AFF;
	color: white;
	font-weight: bold;
}

/* 列表视图样式 */
.list-view {
	background: white;
	border-radius: 15rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.list-item {
	padding: 30rpx 20rpx;
	margin-bottom: 15rpx;
	background: #f8f8f8;
	border-radius: 10rpx;
	cursor: pointer;
	transition: all 0.3s ease;
	border-left: 6rpx solid #007AFF;
}

.list-item:active {
	background: #e8e8e8;
	transform: scale(0.98);
}

.list-item-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 15rpx;
	text-align: left;
	flex-wrap: wrap;
}

.list-item-title {
	font-size: 30rpx;
	font-weight: bold;
	color: #333;
	text-align: left;
	margin-right: 10rpx;
}

.list-item-pet {
	font-size: 24rpx;
	color: #666;
	background: #f0f0f0;
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
}

.list-item-info {
	display: flex;
	align-items: center;
	justify-content: space-between;
	flex-wrap: wrap;
	gap: 10rpx;
}

.list-item-status {
	margin-left: auto;
}

.list-item-time {
	font-size: 26rpx;
	color: #007AFF;
	font-weight: 500;
}

.list-item-repeat {
	font-size: 24rpx;
	color: #666;
	background: #f0f0f0;
	padding: 6rpx 12rpx;
	border-radius: 15rpx;
}

.list-item-status {
	font-size: 24rpx;
	color: white;
	padding: 6rpx 12rpx;
	border-radius: 15rpx;
	font-weight: 500;
}

.list-item-status.status-pending {
	background: #ff9500;
}

.list-item-status.status-completed {
	background: #34c759;
}

.list-item-status.status-unknown {
	background: #8e8e93;
}

/* 日历样式 */
.calendar-section {
	background: white;
	border-radius: 15rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.calendar-header {
	margin-bottom: 20rpx;
}

.calendar-nav {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 20rpx;
}

.nav-btn {
	font-size: 40rpx;
	color: #007AFF;
	cursor: pointer;
	padding: 10rpx 20rpx;
	border-radius: 50%;
	transition: all 0.3s ease;
}

.nav-btn:active {
	background: rgba(0, 122, 255, 0.1);
}

.current-month {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.calendar-weekdays {
	display: flex;
	margin-bottom: 10rpx;
}

.weekday {
	flex: 1;
	text-align: center;
	font-size: 26rpx;
	color: #666;
	font-weight: 500;
}

.calendar-days {
	display: flex;
	flex-wrap: wrap;
}

.calendar-day {
	width: 14.28%;
	height: 80rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	position: relative;
	cursor: pointer;
	border-radius: 8rpx;
	margin: 5rpx 0;
}

.calendar-day:active {
	background: rgba(0, 122, 255, 0.1);
	border-radius: 8rpx;
}

.day-number {
	font-size: 28rpx;
	color: #333;
}

.calendar-day.other-month .day-number {
	color: #ccc;
}

.calendar-day.today .day-number {
	color: #007AFF;
	font-weight: bold;
}

.calendar-day.selected .day-number {
	color: white;
	font-weight: bold;
}

.calendar-day.selected {
	background: #007AFF;
	border-radius: 8rpx;
}

.reminder-dot {
	position: absolute;
	bottom: 8rpx;
	width: 8rpx;
	height: 8rpx;
	background: #ff6b6b;
	border-radius: 50%;
}

.calendar-day.has-reminder .reminder-dot {
	background: #ff6b6b;
}

/* 提醒列表样式 */
.reminder-section {
	background: white;
	border-radius: 15rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
	padding-bottom: 10rpx;
	border-bottom: 2rpx solid #f0f0f0;
}

.reminder-list {
	
}

.reminder-item {
	display: flex;
	align-items: center;
	padding: 20rpx;
	margin-bottom: 15rpx;
	background: #f8f8f8;
	border-radius: 10rpx;
	cursor: pointer;
	transition: all 0.3s ease;
	border-left: 6rpx solid #007AFF;
}

.reminder-item:active {
	background: #e8e8e8;
	transform: scale(0.98);
}

.reminder-icon {
	margin-right: 20rpx;
}

.reminder-icon .icon {
	font-size: 40rpx;
}

.reminder-info {
	flex: 1;
}

.reminder-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 10rpx;
}

.reminder-header .reminder-status {
	margin-left: auto;
}

.reminder-title {
	font-size: 30rpx;
	font-weight: bold;
	color: #333;
	margin-right: 10rpx;
}

.reminder-pet {
	font-size: 24rpx;
	color: #666;
	background: #f0f0f0;
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
}

.reminder-type-container {
	display: flex;
	align-items: center;
	margin-bottom: 10rpx;
	flex-wrap: wrap;
}

.reminder-pet-highlight {
	font-size: 24rpx;
	font-weight: bold;
	color: white;
	background: #FF9500;
	padding: 6rpx 12rpx;
	border-radius: 20rpx;
	white-space: nowrap;
	margin-left: 10rpx;
	text-align: center;
	border: 2rpx solid rgba(255, 149, 0, 0.5);
}

.reminder-details {
	display: flex;
	align-items: center;
	justify-content: space-between;
	gap: 15rpx;
}

.reminder-type {
	font-size: 26rpx;
	color: #007AFF;
	font-weight: 500;
}

.reminder-repeat {
	font-size: 24rpx;
	color: #666;
	background: #f0f0f0;
	padding: 6rpx 12rpx;
	border-radius: 15rpx;
}

.reminder-status {
	font-size: 24rpx;
	color: white;
	padding: 6rpx 12rpx;
	border-radius: 15rpx;
	font-weight: 500;
}

.reminder-status.status-pending {
	background: #ff9500;
}

.reminder-status.status-completed {
	background: #34c759;
}

.reminder-status.status-unknown {
	background: #8e8e93;
}

/* 空状态样式 */
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 20rpx;
	background: white;
	border-radius: 15rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.empty-text {
	font-size: 28rpx;
	color: #999;
}

/* 加载状态样式 */
.loading-state {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 100rpx 20rpx;
	background: white;
	border-radius: 15rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.loading-text {
	font-size: 28rpx;
	color: #666;
}

/* 悬浮按钮样式 */
.fab {
	position: fixed;
	right: 40rpx;
	bottom: 40rpx;
	width: 100rpx;
	height: 100rpx;
	background: #007AFF;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 4rpx 20rpx rgba(0, 122, 255, 0.3);
	cursor: pointer;
	transition: all 0.3s ease;
	z-index: 1000;
}

.fab:active {
	transform: scale(0.95);
}

.fab-icon {
	font-size: 48rpx;
	color: white;
	font-weight: bold;
}
</style>